#![allow(dead_code)]
pub struct Solution;

impl Solution {
    // This function takes a string `s` as input and returns the length of the longest substring without repeating characters.
    pub fn length_of_longest_substring(s: String) -> i32 {
        // Initialize variables to keep track of the maximum length of the substring, the start and end indices of the substring, and a set to store unique characters.
        let mut max_length = 0;
        let mut start = 0;
        let mut end = 0;
        let mut set = std::collections::HashSet::new();

        // Iterate through the characters of the string from the start index to the end index.
        while end < s.len() {
            // Get the current character at the end index.
            let current_char = s.chars().nth(end).unwrap();

            // If the set does not contain the current character, it is a new unique character in the substring.
            if !set.contains(&current_char) {
                // Add the current character to the set and move the end index forward.
                set.insert(current_char);
                end += 1;

                // Update the maximum length if the current substring length is greater than the previous maximum length.
                max_length = max_length.max(end - start);
            } else {
                // If the set already contains the current character, it means there is a repeating character in the substring.
                // Remove the character at the start index from the set and move the start index forward.
                let char_to_remove = s.chars().nth(start).unwrap();
                set.remove(&char_to_remove);
                start += 1;
            }
        }

        // Return the maximum length as an i32.
        max_length as i32
    }
}

#[cfg(test)]
mod tests {
    use super::Solution;
    #[test]
    fn test_length_of_longest_substring() {
        // Test case 1: String with unique characters
        assert_eq!(
            Solution::length_of_longest_substring(String::from("abcde")),
            5
        );

        // Test case 2: String with repeated characters
        assert_eq!(
            Solution::length_of_longest_substring(String::from("aabbc")),
            2
        );

        // Test case 3: Empty string
        assert_eq!(Solution::length_of_longest_substring(String::from("")), 0);

        // Test case 4: String with all same characters
        assert_eq!(
            Solution::length_of_longest_substring(String::from("aaaaa")),
            1
        );

        // Test case 5: String with mix of unique and repeated characters
        assert_eq!(
            Solution::length_of_longest_substring(String::from("abccba")),
            3
        );
    }
}
